package com.itwmk.filter;

import com.alibaba.fastjson.JSON;

import com.itwmk.utils.BaseContext;
import com.itwmk.utils.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 判断用户是否登录并过滤请求
 * @author wmk
 */
@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //首先判断用户有没有登录，如果登录直接放行
        Object employee = request.getSession().getAttribute("employee");
        if (employee!=null){
            log.info("employee:" +employee);
            Long eId = (Long) employee;
            BaseContext.setId(eId);
            filterChain.doFilter(request,response);
            return;
        }
        //判断移动端用户有没有登录，如果登录直接放行
        Object user = request.getSession().getAttribute("user");
        if (user!=null){
            log.info("user:" +user);
            Long uId = (Long) user;
            BaseContext.setId(uId);
            filterChain.doFilter(request,response);
            return;
        }
        //不管登没登录
        //定义不需要拦截的请求
        String[] uris={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        String uri = request.getRequestURI();

        boolean checkUri = checkUri(uris, uri);

        //如果符合不需拦截的请求，直接放行
        if (checkUri){
            filterChain.doFilter(request,response);
            return;
        }

        //不符合要求的请求返回登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 匹配拦截规则，true表示匹配成功，false表示没有匹配到
     * @param uris
     * @param uri
     * @return
     */
    private boolean checkUri(String[] uris,String uri) {
        for (String rule:uris) {
            boolean match = PATH_MATCHER.match(rule, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
